<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 增强的strstr（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>C 语言有一个库函数&#xff1a; char *strstr(const char *haystack, const char *needle) &#xff0c;实现在字符串 haystack 中查找第一次出现字符串 needle 的位置&#xff0c;如果未找到则返回 null。</p> 
<p>现要求实现一个strstr的增强函数&#xff0c;可以使用带可选段的字符串来模糊查询&#xff0c;与strstr一样返回首次查找到的字符串位置。</p> 
<p>可选段使用“[]”标识&#xff0c;表示该位置是可选段中任意一个字符即可满足匹配条件。比如“a[bc]”表示可以匹配“ab”或“ac”。</p> 
<p>注意目标字符串中可选段可能出现多次。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>与strstr函数一样&#xff0c;输入参数是两个字符串指针&#xff0c;分别是源字符串和目标字符串。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>与strstr函数不同&#xff0c;返回的是源字符串中&#xff0c;匹配子字符串相对于源字符串地址的偏移&#xff08;从0开始算&#xff09;&#xff0c;如果没有匹配返回-1。</p> 
<p>补充说明&#xff1a;源字符串中必定不包含‘[]’&#xff1b;目标字符串中‘[]’必定成对出现&#xff0c;且不会出现嵌套。</p> 
<p>输入的字符串长度在[1,100]之间。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">abcd<br /> b[cd]</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">1</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">相当于是在源字符串中查找bc或者bd&#xff0c;bc子字符串相对于abcd的偏移是1</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题最简单的解题策略是套皮正则表达式。</p> 
<p>即将第二行输入的目标串直接当成正则表达式使用&#xff0c;因为其中[]的逻辑&#xff0c;刚好就是正则表达式“字符组”的功能。</p> 
<hr /> 
<p>根据考友反馈&#xff0c;本题输入的目标字符串中可能存在其他正则元字符&#xff0c;因此套皮正则表达式解法的结果可能会受到影响&#xff0c;实际考试套皮正则表达式可以拿95%通过率。</p> 
<p></p> 
<p>本题可以使用另一种比较稳健的解法&#xff0c;即将目标串分层&#xff0c;比如目标串 b[cd]&#xff0c;相当于两层&#xff1a;</p> 
<ul><li>第一层可选字符是&#xff1a;b</li><li>第二层可选字符是&#xff1a;cd</li></ul> 
<p>然后利用滑窗&#xff0c;滑窗长度就是目标串的层数&#xff0c;去在源字符串中滑动匹配&#xff0c;比如</p> 
<p><img alt="" height="241" src="https://img-blog.csdnimg.cn/4eb1ca5724d4446da10abad11ff2e711.png" width="615" /></p> 
<p></p> 
<h3>滑窗解法</h3> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">const rl &#61; require(&#34;readline&#34;).createInterface({ input: process.stdin });
var iter &#61; rl[Symbol.asyncIterator]();
const readline &#61; async () &#61;&gt; (await iter.next()).value;

void (async function () {
  const src &#61; await readline();
  const tar &#61; await readline();

  // 将tar字符串转化为levels多层结构&#xff0c;转化逻辑为&#xff1a;tar字符串中&#xff0c;每个[]包含的所有字符作为一层&#xff0c;未被[]包含的单个字符作为一层
  const levels &#61; [];

  // level用于记录[]中的字符
  let level &#61; new Set();
  let isOpen &#61; false;

  for (let c of tar) {
    switch (c) {
      case &#34;[&#34;:
        isOpen &#61; true;
        break;
      case &#34;]&#34;:
        isOpen &#61; false;
        levels.push(level);
        level &#61; new Set();
        break;
      default:
        if (isOpen) {
          level.add(c);
        } else {
          levels.push(new Set([c]));
        }
    }
  }

  console.log(indexOf());

  function indexOf() {
    // 滑动匹配levels.length长度的子串
    for (let i &#61; 0; i &lt;&#61; src.length - levels.length; i&#43;&#43;) {
      let isFind &#61; true;

      for (let j &#61; 0; j &lt; levels.length; j&#43;&#43;) {
        if (!levels[j].has(src[i &#43; j])) {
          isFind &#61; false;
          break;
        }
      }

      if (isFind) {
        return i;
      }
    }

    return -1;
  }
})();
</code></pre> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String src &#61; sc.nextLine();
    String tar &#61; sc.nextLine();

    System.out.println(getResult(src, tar));
  }

  public static int getResult(String src, String tar) {
    // 将tar字符串转化为levels多层结构&#xff0c;转化逻辑为&#xff1a;tar字符串中&#xff0c;每个[]包含的所有字符作为一层&#xff0c;未被[]包含的单个字符作为一层
    ArrayList&lt;HashSet&lt;Character&gt;&gt; levels &#61; new ArrayList&lt;&gt;();

    // level用于记录[]中的字符
    HashSet&lt;Character&gt; level &#61; new HashSet&lt;&gt;();
    boolean isOpen &#61; false;

    for (int i &#61; 0; i &lt; tar.length(); i&#43;&#43;) {
      char c &#61; tar.charAt(i);

      switch (c) {
        case &#39;[&#39;:
          isOpen &#61; true;
          break;
        case &#39;]&#39;:
          isOpen &#61; false;
          levels.add(level);
          level &#61; new HashSet&lt;&gt;();
          break;
        default:
          if (isOpen) {
            level.add(c);
          } else {
            HashSet&lt;Character&gt; tmp &#61; new HashSet&lt;&gt;();
            tmp.add(c);
            levels.add(tmp);
          }
      }
    }

    return indexOf(src, levels);
  }

  public static int indexOf(String src, ArrayList&lt;HashSet&lt;Character&gt;&gt; levels) {
    // 滑动匹配levels.length长度的子串
    for (int i &#61; 0; i &lt;&#61; src.length() - levels.size(); i&#43;&#43;) {
      boolean isFind &#61; true;

      for (int j &#61; 0; j &lt; levels.size(); j&#43;&#43;) {
        if (!levels.get(j).contains(src.charAt(i &#43; j))) {
          isFind &#61; false;
          break;
        }
      }

      if (isFind) return i;
    }

    return -1;
  }
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
src &#61; input()
tar &#61; input()


def indexOf(levels):
    # 滑动匹配levels.length长度的子串
    for i in range(len(src) - len(levels) &#43; 1):
        isFind &#61; True

        for j in range(len(levels)):
            if src[i &#43; j] not in levels[j]:
                isFind &#61; False
                break

        if isFind:
            return i

    return -1


# 核心代码
def getResult():
    # 将tar字符串转化为levels多层结构&#xff0c;转化逻辑为&#xff1a;tar字符串中&#xff0c;每个[]包含的所有字符作为一层&#xff0c;未被[]包含的单个字符作为一层
    levels &#61; []

    # level用于记录[]中的字符
    level &#61; set()
    isOpen &#61; False

    for c in tar:
        if c &#61;&#61; &#39;[&#39;:
            isOpen &#61; True
        elif c &#61;&#61; &#39;]&#39;:
            isOpen &#61; False
            levels.append(level)
            level &#61; set()
        else:
            if isOpen:
                level.add(c)
            else:
                levels.append({c})

    return indexOf(levels)


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h3>正则解法</h3> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61; 2) {
    console.log(getResult(lines[0], lines[1]));
    lines.length &#61; 0;
  }
});

function getResult(src, tar) {
  const res &#61; new RegExp(tar).exec(src);

  if (res &amp;&amp; res.length &gt; 0) {
    return src.indexOf(res[0]);
  } else {
    return -1;
  }
}
</code></pre> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String src &#61; sc.nextLine();
    String tar &#61; sc.nextLine();

    System.out.println(getResult(src, tar));
  }

  public static int getResult(String src, String tar) {
    Matcher matcher &#61; Pattern.compile(tar).matcher(src);

    if (matcher.find()) {
      return src.indexOf(matcher.group());
    } else {
      return -1;
    }
  }
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
import re

src &#61; input()
tar &#61; input()


# 核心代码
def getResult():
    res &#61; re.search(tar, src)

    if res is None:
        return -1
    else:
        return res.start()


# 算法调用
print(getResult())
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>